package controllers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Enumeration;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import data.LinkData;
import data.TransactionData;
import debug.TransactionDebug;

import models.LinkModel;
import models.TransactionModel;

public class PaypalIPNServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {

		Enumeration en = request.getParameterNames();
		// to get validate from paypal.
		StringBuilder str = new StringBuilder();
		// to save to db
		StringBuilder paypalIPN = new StringBuilder();
		str.append("cmd=_notify-validate");
		while (en.hasMoreElements()) {
			String paramName = (String) en.nextElement();
			String paramValue = request.getParameter(paramName);
			str.append("&");
			str.append(paramName);
			str.append("=");
			str.append(URLEncoder.encode(paramValue, "UTF-8"));
			paypalIPN.append("<");
			paypalIPN.append(paramName);
			paypalIPN.append(">");
			paypalIPN.append(paramValue);
			paypalIPN.append("</");
			paypalIPN.append(paramName);
			paypalIPN.append(">");
		}

		// post back to PayPal system to validate
		URL u = new URL("https://www.sandbox.paypal.com/us/cgi-bin/webscr");
		URLConnection uc = u.openConnection();
		uc.setDoOutput(true);
		uc.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		PrintWriter pw = new PrintWriter(uc.getOutputStream());
		pw.println(str);
		pw.close();
		
		BufferedReader in = new BufferedReader(new InputStreamReader(
				uc.getInputStream()));
		String res = in.readLine();
		in.close();
		
		TransactionData tData = new TransactionData();
		TransactionModel transaction = new TransactionModel();
		//Check VERIFIED
		if (res.equals("VERIFIED")) {
			String txn_id = (String) (String) request.getParameter("txn_id");
			String paypal_ipn = (String) paypalIPN.toString();
			String business = (String) request.getParameter("business");
			String payer_email = (String) request.getParameter("payer_email");
			String payer_id = (String) request.getParameter("payer_id");
			int quantity = Integer.parseInt((String) request.getParameter("quantity"));
			String payment_status = (String) request.getParameter("payment_status");
			float payment_fee = Float.parseFloat((String) request.getParameter("payment_fee"));
			String item_name = (String) request.getParameter("item_name");
			String item_number = (String) request.getParameter("item_number");
			String mc_currency = (String) request.getParameter("mc_currency");
			String receiver_id = (String) request.getParameter("receiver_id");
			
			//Set transaction
			transaction.setTransactionId(txn_id);
			transaction.setPaypalIPN(paypal_ipn);
			transaction.setBusiness(business);
			transaction.setPayerEmail(payer_email);
			transaction.setPayerId(payer_id);
			transaction.setQuantity(quantity);
			transaction.setPaymentStatus(payment_status);
			transaction.setPaymentFee(payment_fee);
			transaction.setItemName(item_name);
			transaction.setItemNumber(item_number);
			transaction.setMcCurrency(mc_currency);
			transaction.setReceiverId(receiver_id);
			
			//insert value
			tData.insert(transaction);
			
			//Update link
			if (payment_status.equalsIgnoreCase("completed")) {
				try {
					long id = getId(item_number);
					LinkData linkData = new LinkData();
					LinkModel link = linkData.getLink(id);
					linkData.setPublished(link);
				} catch (Exception e) {}
				
			}
			
			response.setContentType("text/plain");
			
			TransactionDebug.debugWeb(transaction, response);
			
		} else if (res.equals("INVALID")) {
			response.getWriter().println(res);
		}
	}
	
	private long getId(String txt) {
		long id = 0;
		txt = txt.replaceAll("[^0-9]*", "");
		id = new Long(txt);
		return id;
	}
}
